package com.ys.controller.web.account;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ys.config.MenuId;
import com.ys.dto.SubGridConfigDto;
import com.ys.entity.account.TcwAdvanceAccount;
import com.ys.entity.account.TcwAdvanceAccountDetail;
import com.ys.service.sys.CommonApiService;
import com.ys.vo.W;

/**
 * 预支账户管理
 */
@Controller
@RequestMapping("/web/account/tcwAdvanceAccount")
public class WebTcwAdvanceAccountController {
	private static final Logger logger = LoggerFactory.getLogger(WebTcwAdvanceAccountController.class);

	@Autowired
	private CommonApiService<TcwAdvanceAccount> commonApiService;

    /*
     * 新增
     */
    @GetMapping("/toAdd")
    public String toAdd(Model model) {
        try {
            Map<String, Object> extraParam = new HashMap<>();
            //关联数据
            extraParam.put("code", commonApiService.getCommonNextUkey(MenuId.TCW_AdvanceAccount, "Code"));
            extraParam.put("status", 1);
            extraParam.put("accountType", 0);
            model.addAttribute("onProcess", 0);
            commonApiService.toAdd(model, new TcwAdvanceAccount(), MenuId.TCW_AdvanceAccount, extraParam, null);
            
            return "account/tcwAdvanceAccount/toAdd";
        }catch (Exception e) {
            logger.error("新增页面出错：",e.getMessage(),e);
            return W.error(model, e.getMessage());
        }
    }



    public Map<String, Object> getEntity(Long id){
        Map<String,Object> entity = new TcwAdvanceAccount()
        .addLeftJoin("TS_UserBankInfo U ON A.UserBankInfoId = U.Id AND A.AccountType=0")
                .addLeftJoin("TCW_PartnerBankInfo P ON A.PartnerBankInfoId = P.Id AND A.AccountType=1")
                .addField("CASE WHEN A.AccountType=0 THEN U.Vyhzhmc ELSE P.Vyhzhmc END _ys_vyhzhmc")//银行账户名称
                .addField("CASE WHEN A.AccountType=0 THEN U.Vkhh ELSE P.Vkhh END _ys_vkhh")//开户行
                .addField("CASE WHEN A.AccountType=0 THEN U.Vyhzh ELSE P.Vyhzh END _ys_vyhzh")//银行账户编码

            .addLeftJoin("TS_UserInfo B on  B.UserId = A.UserId")
                .addField("B.roleName AS roleName")//负责人岗位
                .addField("(B.UserId + '/' + B.UserName) AS _ys_nameLinked")//账户管理负责人

            .addLeftJoin("TS_OrganizationInfo O on  O.Orgid = A.Orgid")
                .addField("O.OrgName AS orgName")//账户管理部门

            //明细1
            .addLeftJoin("(SELECT Pid, SUM(TotalPrice) AS totalPriceByRecharge FROM TCW_AdvanceAccountDetail  WHERE AdvanceTypeCode ='YZZHLX000' GROUP BY Pid) D1 on D1.Pid = A.Id AND 1=1")
                .addField("ISNULL(D1.totalPriceByRecharge, 0) AS totalPriceByRecharge")//账户备用金额,字段“总额”之和（预支类型为充值）
            //明细2
            .addLeftJoin("(SELECT Pid, SUM(TotalPrice) AS totalPriceByOther FROM TCW_AdvanceAccountDetail  WHERE AdvanceTypeCode NOT IN ('YZZHLX000','YZZHLX001') GROUP BY Pid) D2 on D2.Pid = A.Id AND 1=1")
                .addField("ISNULL(D2.totalPriceByOther, 0) AS totalPriceByOther")//台账总金额
            //明细3
            .addLeftJoin("(SELECT Pid, SUM(TotalPrice) AS totalPriceBySubmit FROM TCW_AdvanceAccountDetail  WHERE AdvanceTypeCode ='YZZHLX001' GROUP BY Pid) D3 on D3.Pid = A.Id AND 1=1")
                .addField("ISNULL(D3.totalPriceBySubmit, 0) AS totalPriceBySubmit")//台账报销金额,字段“总额”之和（预支类型为报销）

                .setId(id)
                .queryFirstMap();

        return entity;
    }


    public Map<String, Object> setExtraParam(Map<String,Object> entity){
        Map<String, Object> extraParam = new HashMap<String, Object>();
        //关联数据
        if(entity.get("_ys_vyhzhmc")!=null)extraParam.put("_ys_vyhzhmc", entity.get("_ys_vyhzhmc"));
        if(entity.get("_ys_vkhh")!=null)extraParam.put("_ys_vkhh", entity.get("_ys_vkhh"));
        if(entity.get("_ys_vyhzh")!=null)extraParam.put("_ys_vyhzh", entity.get("_ys_vyhzh"));
        if(entity.get("orgName")!=null)extraParam.put("orgName", entity.get("orgName"));
        if(entity.get("roleName")!=null)extraParam.put("roleName", entity.get("roleName"));
        if(entity.get("_ys_nameLinked")!=null)extraParam.put("_ys_nameLinked", entity.get("_ys_nameLinked"));
        if(entity.get("totalPriceByRecharge")!=null)extraParam.put("totalPriceByRecharge", entity.get("totalPriceByRecharge"));
        if(entity.get("totalPriceByOther")!=null)extraParam.put("totalPriceByOther", entity.get("totalPriceByOther"));
        if(entity.get("totalPriceBySubmit")!=null)extraParam.put("totalPriceBySubmit", entity.get("totalPriceBySubmit"));
        if(entity.get("accountType")!=null)extraParam.put("accountTypeByModal", entity.get("accountType"));

        BigDecimal totalPriceByRecharge = BigDecimal.ZERO;//账户备用金额
        BigDecimal totalPriceByOther = BigDecimal.ZERO;//台账总金额
        BigDecimal totalPriceBySubmit = BigDecimal.ZERO;//台账报销金额
        if(entity.get("totalPriceByRecharge")!=null)totalPriceByRecharge = new BigDecimal(entity.get("totalPriceByRecharge").toString());//账户备用金额
        if(entity.get("totalPriceByOther")!=null)totalPriceByOther = new BigDecimal(entity.get("totalPriceByOther").toString());//台账总金额
        if(entity.get("totalPriceBySubmit")!=null)totalPriceBySubmit = new BigDecimal(entity.get("totalPriceBySubmit").toString());//台账报销金额

        //计算：账户可用金额 = 账户备用金额-台账总金额+台账报销金额
        BigDecimal canUseMoney = totalPriceByRecharge.subtract(totalPriceByOther).add(totalPriceBySubmit);
        extraParam.put("canUseMoney", canUseMoney);
        return extraParam;
    }

    /*
     * 编辑
     */
    @GetMapping("/toEdit")
    public String toEdit(Model model, Long id) {
        try {
            model.addAttribute("onProcess", 0);
            Map<String,Object> entity = getEntity(id);
            Map<String, Object> extraParam = setExtraParam(entity);
            model.addAttribute("_ys_vyhzhmc", entity.get("_ys_vyhzhmc"));
            commonApiService.toEdit(model,id, new TcwAdvanceAccount(), MenuId.TCW_AdvanceAccount, extraParam, null);
             
            return "account/tcwAdvanceAccount/toEdit";
        }catch (Exception e) {
            logger.error("编辑页面出错：",e.getMessage(),e);
            return W.error(model, e.getMessage());
        }
    }


    /*
     * 详情
     */
    @GetMapping("/toDetail")
    public String toDetail(Model model, Long id) {
        try {
            model.addAttribute("onProcess", 1);
            Map<String,Object> entity = getEntity(id);
            Map<String, Object> extraParam = setExtraParam(entity);
            model.addAttribute("_ys_vyhzhmc", entity.get("_ys_vyhzhmc"));
            return commonApiService.toDetail(model,id, new TcwAdvanceAccount(), MenuId.TCW_AdvanceAccount, extraParam, null);
            //return "account/tcwAdvanceAccount/toEdit";
        }catch (Exception e) {
            logger.error("详情页面出错：",e.getMessage(),e);
            return W.error(model, e.getMessage());
        }
    }


    /*
     * 明细
     */
    @GetMapping("/toList")
    public String toList(Model model, Long id) {
        try {
            model.addAttribute("onProcess", 1);
            Map<String,Object> entity = getEntity(id);
            Map<String, Object> extraParam = setExtraParam(entity);

            // 子列表配置信息
            SubGridConfigDto subGridConfig = commonApiService.getSubGrid(MenuId.TCW_AdvanceAccountDetail, new ArrayList<>());

            return commonApiService.toEdit(model,id, new TcwAdvanceAccount(), MenuId.TCW_AdvanceAccountDetail, extraParam, subGridConfig);
        }catch (Exception e) {
            logger.error("详情页面出错：",e.getMessage(),e);
            return W.error(model, e.getMessage());
        }
    }




    /*
     * 新增
     */
    @GetMapping("/toAddListByEdit")
    public String toAddListByEdit(Model model) {
        try {
            // 子列表配置信息
            SubGridConfigDto subGridConfig = commonApiService.getSubGrid(MenuId.TCW_AdvanceAccountDetail, new ArrayList<>());
            model.addAttribute("onProcess", 0);
            return commonApiService.toAdd(model, new TcwAdvanceAccount(), MenuId.TCW_AdvanceAccountDetail, null, subGridConfig);
        }catch (Exception e) {
            logger.error("新增页面出错：",e.getMessage(),e);
            return W.error(model, e.getMessage());
        }
    }


    /*
     * 明细
     */
    @GetMapping("/toListByEdit")
    public String toListByEdit(Model model, Long id) {
        try {
            model.addAttribute("onProcess", 1);
            Map<String,Object> entity = getEntity(id);
            Map<String, Object> extraParam = setExtraParam(entity);

            List<Map<String, Object>> itemList = new TcwAdvanceAccountDetail()
                    .addLeftJoin("TCW_AdvanceAccount P ON P.Id = A.Pid")//预支账户管理
                    .addField("P.Code AS pCode")//预支账户编码
                    .addField("P.Name AS pName")//预支账户名称

                    .addLeftJoin("TB_AdvanceType T ON T.Code = A.AdvanceTypeCode")//预支类型
                    .addField("T.Name AS advanceTypeName")//预支类型名称

                    .addLeftJoin("TB_CompanyInfo C ON C.Vid = A.CompanyInfoVid")//公司信息表
                    .addField("C.Vname AS companyName")//公司名称

                    .addLeftJoin("THR_OperateCompanyApply OC ON OC.Vgsbm = A.Vgsbm")//运营公司表
                    .addField("OC.Vgsjc AS vgsjc")//公司简称

                    .addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeId ")
                    .addField("U.UserId + '/' + U.UserName AS userName")//新增人员
                    .addField("U.DeptName AS deptName")//新增部门

                    .setPid(id)
                    .queryMap();

            // 子列表配置信息
            SubGridConfigDto subGridConfig = commonApiService.getSubGrid(MenuId.TCW_AdvanceAccountDetail, itemList);

            return commonApiService.toEdit(model,id, new TcwAdvanceAccount(), MenuId.TCW_AdvanceAccountDetail, extraParam, subGridConfig);
            //return "account/tcwAdvanceAccountDetail/toEdit";
        }catch (Exception e) {
            logger.error("详情页面出错：",e.getMessage(),e);
            return W.error(model, e.getMessage());
        }
    }



}






